package com.zoffy.catdiarybackend.tasks;

import com.zoffy.catdiarybackend.model.entity.Article;
import com.zoffy.catdiarybackend.service.ArticleService;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
public class ArticleCollaborationTasks {
    @Autowired
    private RedisTemplate<Object,Object> redisTemplate;
    @Resource
    private ArticleService articleService;
    @Scheduled(fixedDelay = 5)
    public void updateRedisArticle(){
        Set<Object> articleCollaborationActiveSet = redisTemplate.opsForSet().members("article_collaboration_active_set");
        if (articleCollaborationActiveSet==null){
            return;
        }
        for(Object id:articleCollaborationActiveSet){
            String key=(String) id;
            String[] strings = key.split("_");
            String room=strings[strings.length-1];
            String content =(String) redisTemplate.opsForValue().get(key);
            if (content==null){
                continue;
            }
            Article article=new Article();
            article.setId(Long.parseLong(room));
            article.setContent(content);
            articleService.updateById(article);
        }
    }
}
